package com.aitaoxue.palx.ui;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

import java.io.File;
import java.util.Properties;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.AppManager;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.db.InfoDBHelper;
import com.aitaoxue.palx.db.course.CourseContext;
import com.aitaoxue.palx.fragment.MainFragment;
import com.aitaoxue.palx.interf.BaseViewInterface;
import com.aitaoxue.palx.service.LoginService;
import com.aitaoxue.palx.ui.dialog.CommonToast;
import com.aitaoxue.palx.util.IntentUtil;
import com.aitaoxue.palx.viewpagefragment.CourseViewPagerFragment;
import com.aitaoxue.palx.widget.MyFragmentTabHost;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sea_monster.resource.Resource;

/**
 * 采用butterknife注入框架
 * 
 * @author earthgee
 * 
 */
public class MainActivity extends FragmentActivity implements
		BaseViewInterface, OnTabChangeListener, OnClickListener, Callback {

	private static final String TAG = FragmentActivity.class.getSimpleName();

	// 融云推送测试
	public static final String PUSH_TEST = "test";

	private long lastTime = 0;

	@InjectView(android.R.id.tabhost)
	MyFragmentTabHost mTabHost;

	private LocationClient mLocationClient = null;
	private String city = null;
	private BDLocationListener myListener = new MyLocationListener();

	private Handler handler;

	private DownloadManager downloadManager;

	private ReceiveMessageBroadcastReceiver mBroadCastReceiver;

	private String localAppPath;
	
	/**
	 * 布局文件为activity_main
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ButterKnife.inject(this);

		getActionBar().hide();

		final Conversation.ConversationType[] conversationTypes = {
				Conversation.ConversationType.PRIVATE,
				Conversation.ConversationType.DISCUSSION,
				Conversation.ConversationType.GROUP,
				Conversation.ConversationType.SYSTEM,
				Conversation.ConversationType.APP_PUBLIC_SERVICE,
				Conversation.ConversationType.PUBLIC_SERVICE };

		handler = new Handler(this);
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				RongIM.getInstance().setOnReceiveUnreadCountChangedListener(
						mCountListener, conversationTypes);
			}
		}, 300);

		initView();

		initData();

		initLocation();
		
		startService(new Intent(this, LoginService.class));
	}

	/**
	 * 初始化tabhost
	 * 
	 */
	public void initView() {
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
		mTabHost.getTabWidget().setShowDividers(0);

		initTabs();

		mTabHost.setCurrentTab(2);
		mTabHost.setOnTabChangedListener(this);

		// int size = getSupportFragmentManager().getFragments().size();
		// TLog.log(TAG, ""+size);
		AppManager.getAppManager().addActivity(this);

		// 检测更新
		AitaoXueApi.AppUpdate(mUpdateHandler);
	}

	public void initData() {
		IntentFilter intentfilter = new IntentFilter();
		intentfilter.addAction(IntentUtil.PUSH_NEW_ORDER);
		if (mBroadCastReceiver == null) {
			mBroadCastReceiver = new ReceiveMessageBroadcastReceiver();
		}
		this.registerReceiver(mBroadCastReceiver, intentfilter);

		queryIfHasUnreadOrder();
	}

	private void initLocation() {
		city = AppContext.getInstance().getProperty("user.city");

		if (city == null) { // 开始定位
			mLocationClient = new LocationClient(AppContext.getInstance());
			mLocationClient.registerLocationListener(myListener);

			LocationClientOption option = new LocationClientOption();
			option.setCoorType("bd09ll");
			option.setOpenGps(true);
			option.setIsNeedAddress(true);

			mLocationClient.setLocOption(option);
			mLocationClient.start();
		}
	}

	/**
	 * 初始化tab
	 */
	private void initTabs() {
		MainTab[] tabs = MainTab.values();
		final int size = tabs.length;
		for (int i = 0; i < size; i++) {
			MainTab mainTab = tabs[i];
			TabSpec tab = mTabHost.newTabSpec(getString(mainTab.getResName()));

			View indicator = LayoutInflater.from(getApplicationContext())
					.inflate(R.layout.tab_indicator, null);

			ImageView icon = (ImageView) indicator.findViewById(R.id.tab_icon);
			icon.setImageResource(mainTab.getResIcon());
			TextView title = (TextView) indicator.findViewById(R.id.tab_title);
			// if (i == 2) {
			// title.setVisibility(View.GONE);
			// icon.setVisibility(View.GONE);
			// mTabHost.setNoTabChangedTag(getString(mainTab.getResName()));
			// }
			title.setText(getString(mainTab.getResName()));
			tab.setIndicator(indicator);
			tab.setContent(new TabContentFactory() {

				@Override
				public View createTabContent(String arg0) {
					return new View(MainActivity.this);
				}
			});

			mTabHost.addTab(tab, mainTab.getClz(), null);
		}
	}

	@Override
	public void onTabChanged(String arg0) {
		final int size = mTabHost.getTabWidget().getTabCount();
		for (int i = 0; i < size; i++) {
			View v = mTabHost.getTabWidget().getChildAt(i);
			if (i == mTabHost.getCurrentTab()) {
				v.findViewById(R.id.tab_icon).setSelected(true);
				v.findViewById(R.id.tab_title).setSelected(true);
			} else {
				v.findViewById(R.id.tab_icon).setSelected(false);
				v.findViewById(R.id.tab_title).setSelected(false);
			}
		}

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {

		default:
			break;
		}
	}

	/**
	 * 展示快速操作dialog
	 */
	private void showQuickOption() {
		QuickOptionDialog dialog = new QuickOptionDialog(MainActivity.this);
		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		changeNewVersionTag();
	}

	private class MyLocationListener implements BDLocationListener {

		@SuppressWarnings("serial")
		@Override
		public void onReceiveLocation(BDLocation location) {
			final String city = location.getCity();
			final double latitude = location.getLatitude();
			final double longitude = location.getLongitude();

			// 关闭定位
			mLocationClient.stop();

			final int cityid = InfoDBHelper.getCityId(city);

			// 保存城市和经纬度
			AppContext.getInstance().setProperties(new Properties() {
				{
					setProperty("user.cityid", String.valueOf(cityid));
					setProperty("user.city", city);
					setProperty("user.latitude", String.valueOf(latitude));
					setProperty("user.longitude", String.valueOf(longitude));
				}
			});

			if (city != null) {
				notifyCityChanged(city);
			}
		}
	}

	private void notifyCityChanged(String city) {
		MainFragment mainFragment = (MainFragment) getSupportFragmentManager()
				.findFragmentByTag(
						getResources().getString(R.string.main_tab_name_home));
		if (mainFragment != null) {
			mainFragment.setCity(city);
		}
	}

	@Override
	protected void onStop() {
		if (mLocationClient != null) {
			mLocationClient.stop();
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		if (mLocationClient != null && myListener != null) {
			mLocationClient = null;
			myListener = null;
		}

		this.unregisterReceiver(mBroadCastReceiver);
		super.onDestroy();
	}

	@Override
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		return false;
	}

	public RongIM.OnReceiveUnreadCountChangedListener mCountListener = new RongIM.OnReceiveUnreadCountChangedListener() {

		@Override
		public void onMessageIncreased(int count) {
			// 获得tab indicator
			View parent = mTabHost.getTabWidget().getChildAt(3);
			TextView dot = (TextView) parent.findViewById(R.id.red_hat);

			if (count == 0) {
				dot.setVisibility(View.GONE);
			} else if (count > 0 && count < 100) {
				dot.setVisibility(View.VISIBLE);
				dot.setText(count + "");
			} else {
				dot.setVisibility(View.VISIBLE);
				dot.setText("...");
			}
		}
	};

	@SuppressWarnings("deprecation")
	public void onBackPressed() {
		if (System.currentTimeMillis() - lastTime > 2000) {
			CommonToast toast = new CommonToast(this);
			toast.setMessage("再按一次退出应用");
			toast.show();
			lastTime = System.currentTimeMillis();
		} else {
			if (RongIM.getInstance() != null) {
				// RongIM.getInstance().disconnect(true);

				AppManager.getAppManager().finishAllActivity();
				// finish();
				// Process.killProcess(Process.myPid());
			}
		}
	}

	private class ReceiveMessageBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent intent) {
			int unReadCount = CourseContext.getInstance().queryAllCount();

			// 收到广播,改变ui
			View parent = mTabHost.getTabWidget().getChildTabViewAt(0);
			TextView dot = (TextView) parent.findViewById(R.id.red_hat);
			if (unReadCount > 0) {
				dot.setVisibility(View.VISIBLE);

				dot.setText(unReadCount > 100 ? "..." : "" + unReadCount);
			} else {
				dot.setVisibility(View.GONE);
			}

			if (intent.getBooleanExtra("fromreceiver", false)) {
				if (intent.getStringExtra("type").equals("6")) {
					// 刷新待处理页面
					CourseViewPagerFragment fragment = (CourseViewPagerFragment) getSupportFragmentManager()
							.findFragmentByTag(
									getResources().getString(
											R.string.main_tab_name_course));

					if (fragment != null) {
						fragment.refreshNotDeal();
					}
				}
			}

			String type = intent.getStringExtra("type");

			if (type != null && type.equals("1")) {
				// 刷新进行中页面
				CourseViewPagerFragment fragment = (CourseViewPagerFragment) getSupportFragmentManager()
						.findFragmentByTag(
								getResources().getString(
										R.string.main_tab_name_course));

				if (fragment != null) {
					fragment.refreshDealing();
				}
			} else if (type != null && type.equals("2")) {
				// 刷新进行中页面及已完结页面
				CourseViewPagerFragment fragment2 = (CourseViewPagerFragment) getSupportFragmentManager()
						.findFragmentByTag(
								getResources().getString(
										R.string.main_tab_name_course));
				if (fragment2 != null) {
					fragment2.refreshDealed();
				}
			}
		}
	}

	private void queryIfHasUnreadOrder() {
		int unReadCount = CourseContext.getInstance().queryAllCount();

		// 收到广播,改变ui
		View parent = mTabHost.getTabWidget().getChildTabViewAt(0);
		TextView dot = (TextView) parent.findViewById(R.id.red_hat);
		if (unReadCount > 0) {
			dot.setVisibility(View.VISIBLE);

			dot.setText(unReadCount > 100 ? "..." : "" + unReadCount);
		}
	}

	private void changeNewVersionTag() {
		View view = mTabHost.getTabWidget().getChildTabViewAt(4);
		TextView dot = (TextView) view.findViewById(R.id.red_hat);
		String newVersion = AppContext.getInstance().getProperty("new_version");
		if (newVersion != null && newVersion.equals("true")) {
			dot.setVisibility(View.VISIBLE);
			
			dot.setText("new");
		}
	}

	private AsyncHttpResponseHandler mUpdateHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);
				String code = json.getString("code");
				if (code.equals("9998")) {
					// 有更新
					// 显示dialog
					AlertDialog.Builder builder = new AlertDialog.Builder(
							MainActivity.this);
					View view = LayoutInflater.from(MainActivity.this).inflate(
							R.layout.dialog_update, null);
					builder.setView(view);
					Button positiveBotton = (Button) view
							.findViewById(R.id.btn_ok);
					Button negativeButton = (Button) view
							.findViewById(R.id.btn_cancel);

					final AlertDialog dialog = builder.create();
					dialog.show();

					positiveBotton.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialog.dismiss();
							if (Environment.getExternalStorageState().equals(
									Environment.MEDIA_MOUNTED)) {
								Toast.makeText(MainActivity.this,
										"正在更新,请在状态栏上查看详情", Toast.LENGTH_SHORT)
										.show();
								// 更新
								update();
							} else {
								Toast.makeText(MainActivity.this, "请插入sd卡",
										Toast.LENGTH_SHORT).show();
							}

						}
					});

					negativeButton.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							dialog.dismiss();
						}
					});
				} else if (code.equals("9997")) {
					// 没有更新
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}
	};

	private void update() {
		AppContext.getInstance().setProperty("new_version", "true");

		changeNewVersionTag();
		localAppPath = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/download/aitaoxue_teacher.apk";
		File file = new File(localAppPath);
		if (file.exists()) {
			file.delete();
		}

		downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

		String url = "https://sm.wdjcdn.com/release/files/jupiter/5.9.1.8951/wandoujia-wandoujia_web.apk";
		Uri source = Uri.parse(url);
		DownloadManager.Request request = new DownloadManager.Request(source);
		request.setAllowedNetworkTypes(Request.NETWORK_MOBILE
				| Request.NETWORK_WIFI);
		request.setAllowedOverRoaming(false);

		MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
		String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap
				.getFileExtensionFromUrl(url));
		request.setMimeType(mimeString);

		request.setShowRunningNotification(true);
		request.setVisibleInDownloadsUi(true);

		request.setDestinationInExternalPublicDir("/download",
				"aitaoxue_teacher.apk");
		request.setTitle("家教版下载中");

		long id = downloadManager.enqueue(request);

		AppContext.getInstance().setProperty("app_download_id",
				String.valueOf(id));

		registerReceiver(downloadReceiver, new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			long nowId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,
					0l);
			if (Long.parseLong(AppContext.getInstance().getProperty(
					"app_download_id")) == nowId) {
				// 下载完成
				Toast.makeText(MainActivity.this, "下载完成,即将安装",
						Toast.LENGTH_SHORT).show();

				// 安装
				Intent i = new Intent(Intent.ACTION_VIEW);
				String filePath = localAppPath;
				i.setDataAndType(Uri.parse("file://" + filePath),
						"application/vnd.android.package-archive");
				context.startActivity(i);
			}
		}
	};
}
